﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace StartupTaskRunner.Logging
{
    /// <summary>
    /// Provides a context for executing a command. the context is used for tracing purposes.
    /// </summary>
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    public class LogContext : IDisposable
    {
        Stopwatch _stopwatch = null;
        string _name = null;

        // Track whether Dispose has been called.
        private bool disposed = false;

        public LogContext(string name)
        {
            Logger.WriteMessage("Starting execution of {0}", name);
            _name = name;
            _stopwatch = new Stopwatch();
            _stopwatch.Start();
        }

        // Implement IDisposable.
        // Do not make this method virtual.
        // A derived class should not be able to override this method.
        public void Dispose()
        {
            _stopwatch.Stop();
             Logger.WriteMessage("Finished execution of {0}", _name);
             Logger.WriteMessage("Execution of {0} took {1} ms", _name, _stopwatch.ElapsedMilliseconds);

            Dispose(true);
            // This object will be cleaned up by the Dispose method.
            // Therefore, you should call GC.SupressFinalize to
            // take this object off the finalization queue
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        // Dispose(bool disposing) executes in two distinct scenarios.
        // If disposing equals true, the method has been called directly
        // or indirectly by a user's code. Managed and unmanaged resources
        // can be disposed.
        // If disposing equals false, the method has been called by the
        // runtime from inside the finalizer and you should not reference
        // other objects. Only unmanaged resources can be disposed.
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this.disposed)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                    
                }

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                // If disposing is false,
                // only the following code is executed.

                // Note disposing has been done.
                disposed = true;

            }
        }

    }
}
